package com.lu.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lu.reggie.common.R;
import com.lu.reggie.entity.Category;
import com.lu.reggie.service.ICategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 菜品及套餐分类 前端控制器
 * </p>
 *
 * @author 况山云
 * @since 2022-08-22
 */
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private ICategoryService iCategoryService;

    /**
     * 菜品添加
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category) {
        log.info("category:{}", category);
        iCategoryService.save(category);
        return R.success("新增分类成功!");
    }

    /**
     * 分类页面分页
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize) {
        //分页构造器
        Page pages = new Page(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //降序
        queryWrapper.orderByAsc(Category::getSort);
        //查询
        iCategoryService.page(pages, queryWrapper);
        //返回信息
        return R.success(pages);
    }

    /**
     * 删除分类
     * @param
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long id) {
        log.info("删除的菜品为:{}", iCategoryService.getById(id));
        System.out.println(id);
        iCategoryService.remove(id);
        return R.success("删除成功!");
    }


    /**
     * 修改菜品信息
     * @param category
     * @return
     */
    @PutMapping
    public R<String> updateById(@RequestBody Category category) {
        log.info("修改的菜品为:{}", category);
        iCategoryService.updateById(category);
        return R.success("修改成功!");
    }

    /**
     * 新增菜品下拉分类数据
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category) {
        //条件
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        queryWrapper.eq(category.getType() != null, Category::getType, category.getType());
        //排序
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = iCategoryService.list(queryWrapper);
        return R.success(list);
    }
}
